package com.atguigu.deadlocdemo;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class DeadLockDemo {
     static Lock lockA = new ReentrantLock();
     static Lock lockB = new ReentrantLock();

    public static void main(String[] args) {
        new Thread(()->{
            lockA.lock();
            try {
                System.out.println(Thread.currentThread().getName()+"\t" +"自己持有A锁，试图获得B锁");
                try {TimeUnit.SECONDS.sleep(1);} catch (InterruptedException e) {e.printStackTrace();}
                lockB.lock();
                try {
                    System.out.println(Thread.currentThread().getName()+"\t" +"成功获得B锁");
                } finally {
                    lockB.unlock();
                }
            } finally {
                   lockA.unlock();
            }
        },"A").start();

        new Thread(()->{
            lockB.lock();
            try {
                System.out.println(Thread.currentThread().getName()+"\t" +"自己持有B锁，试图获得A锁");
                try {TimeUnit.SECONDS.sleep(1);} catch (InterruptedException e) {e.printStackTrace();}
                lockA.lock();
                try {
                    System.out.println(Thread.currentThread().getName()+"\t" +"成功获得A锁");
                } finally {
                    lockA.unlock();
                }
            } finally {
                lockB.unlock();
            }
        },"B").start();

    }
}
